package cn.edu.hstc.wm.https;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.util.Log;
import cn.edu.hstc.wm.AppConfigs;

/**
 * 网络连接工具类
 * 
 */
public class HttpUtils {

	public static final int METHOD_GET = 1;
	public static final int METHOD_POST = 2;
	public static final String BASE_URL = "http://";

	// 网络连接部分
	public static String postByHttpURLConnection(String strUrl, NameValuePair... nameValuePairs) {
		return CustomHttpURLConnection.PostFromWebByHttpURLConnection(strUrl, nameValuePairs);
	}

	public static String getByHttpURLConnection(String strUrl, NameValuePair... nameValuePairs) {
		return CustomHttpURLConnection.GetFromWebByHttpUrlConnection(strUrl, nameValuePairs);
	}

	public static String postByHttpClient(Context context, String strUrl, NameValuePair... nameValuePairs) {
		return CustomHttpClient.PostFromWebByHttpClient(context, strUrl, nameValuePairs);
	}

	public static String getByHttpClient(Context context, String strUrl, NameValuePair... nameValuePairs) throws Exception {
		return CustomHttpClient.getFromWebByHttpClient(context, strUrl, nameValuePairs);
	}

	/**
	 * 使用get 请求,请求参数放在url中,不安全
	 * 
	 * @param url
	 *            发送请求的URL
	 * @return 服务器响应字符串
	 * @throws Exception
	 */
	public static String getRequest(final String url) throws Exception {
		FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
			@Override
			public String call() throws Exception {
				// 创建HttpGet对象。
				HttpGet httpGet = new HttpGet(url);
				HttpClient httpClient = new DefaultHttpClient();
				// 发送GET请求
				HttpResponse httpResponse = httpClient.execute(httpGet);
				// 如果服务器成功地返回响应
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					// 获取服务器响应字符串
					String result = EntityUtils.toString(httpResponse.getEntity());
					System.out.println(result);
					return result;
				}
				return null;
			}
		});
		new Thread(task).start();
		return task.get();
	}

	/**
	 * post请求,请求参数不暴露,so..
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param params
	 *            请求参数
	 * @return 服务器响应字符串
	 * @throws Exception
	 */
	public static String postRequest(final String url, final Map<String, String> rawParams) throws Exception {
		FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
			@Override
			public String call() throws Exception {
				// 创建HttpPost对象。
				HttpPost post = new HttpPost(url);
				// http 请求 参数设置
				HttpParams httpParameters = new BasicHttpParams();
				// 设置超时连接
				HttpConnectionParams.setConnectionTimeout(httpParameters, AppConfigs.HTTP_TIMEOUT);
				// HttpClient
				DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

				// 传递的参数
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				for (String key : rawParams.keySet()) {
					// 封装请求参数
					params.add(new BasicNameValuePair(key, rawParams.get(key)));
				}

				// 设置请求参数
				post.setEntity(new UrlEncodedFormEntity(params, AppConfigs.HTTP_CHARSET_UTF));

				// 发送POST请求得到响应内容
				HttpResponse httpResponse = httpClient.execute(post);

				// 如果服务器成功地返回响应
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					// 获取服务器响应字符串
					String result = EntityUtils.toString(httpResponse.getEntity(), AppConfigs.HTTP_CHARSET_UTF);
					System.out.println(result);
					return result;
				}
				return null;
			}
		});
		new Thread(task).start();
		return task.get();
	}

	/**
	 * 远程访问服务器
	 * 
	 * @param uri
	 *            服务器地址
	 * @param params
	 *            参数
	 * @param method
	 *            访问方式get/post
	 * @return HttpEntity 实体类,后期解析出String 还是Stream流
	 * @throws IOException
	 */
	public static HttpEntity getEntity(String uri, ArrayList<BasicNameValuePair> params, int method) throws IOException {
		// 返回的实体内容
		HttpEntity entity = null;
		// http 请求 参数设置
		HttpParams httpParameters = new BasicHttpParams();
		// 设置超时
		HttpConnectionParams.setConnectionTimeout(httpParameters, 10 * 1000);
		// 创建HttpClient
		HttpClient client = new DefaultHttpClient(httpParameters);
		// 请求
		HttpUriRequest request = null;

		switch (method) {

		// get请求
		case METHOD_GET:
			StringBuffer sb = null;
			if (uri.indexOf("http") == 0) {
				sb = new StringBuffer(uri);
			} else {
				sb = new StringBuffer(BASE_URL + uri);
			}
			if (params != null && !params.isEmpty()) {
				// 添加参数
				sb.append("?");
				for (BasicNameValuePair param : params) {
					sb.append(param.getName()).append("=").append(param.getValue()).append("&");
				}
				// 减去最后一个多余的
				sb.deleteCharAt(sb.length() - 1);
			}
			// 创建 HttpGet
			request = new HttpGet(sb.toString());
			break;

		// post请求
		case METHOD_POST:
			if (uri.indexOf("http") == 0) {
				request = new HttpPost(uri);
			} else {
				request = new HttpPost(BASE_URL + uri);
			}
			if (params != null && !params.isEmpty()) {
				UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(params, AppConfigs.HTTP_CHARSET_UTF);
				((HttpPost) request).setEntity(reqEntity);
			}
			break;
		}
		// 响应
		HttpResponse response = client.execute(request);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			entity = response.getEntity();
		}
		return entity;
	}

	/**
	 * 访问服务器，返回IO流
	 * 
	 * @param uri
	 * @param params
	 * @param method
	 * @return InputStream
	 * @throws IOException
	 */
	public static InputStream getInputStream(String uri, ArrayList<BasicNameValuePair> params, int method) throws IOException {
		HttpEntity httpEntity = getEntity(uri, params, method);
		if (httpEntity == null) {
			return null;
		}

		return httpEntity.getContent();
	}

	// ------------------------------------------------------------------------------------------
	// 网络连接判断
	// 判断是否有网络
	// public static boolean isNetworkAvailable(Context context) {
	// return NetWorkHelper.isNetworkAvailable(context);
	// }

	// 判断mobile网络是否可用
	public static boolean isMobileDataEnable(Context context) {
		String TAG = "httpUtils.isMobileDataEnable()";
		try {
			return NetWorkHelper.isMobileDataEnable(context);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			// Log.e(TAG, e.getMessage());
			e.printStackTrace();
			return false;
		}
	}

	// 判断wifi网络是否可用
	public static boolean isWifiDataEnable(Context context) {
		String TAG = "httpUtils.isWifiDataEnable()";
		try {
			return NetWorkHelper.isWifiDataEnable(context);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
			return false;
		}
	}

	// 设置Mobile网络开关
	public static void setMobileDataEnabled(Context context, boolean enabled) {
		String TAG = "httpUtils.setMobileDataEnabled";
		try {
			NetWorkHelper.setMobileDataEnabled(context, enabled);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Log.e(TAG, e.getMessage());
			e.printStackTrace();
		}
	}

	// 判断是否为漫游
	public static boolean isNetworkRoaming(Context context) {
		return NetWorkHelper.isNetworkRoaming(context);
	}
}
